<template>
  <div class="app-container" v-loading="loading">
    <div class="search-bar">
      <div>
        <span class="label">时间范围</span>
        <el-date-picker
          v-model="searchMonth"
          type="monthrange"
          align="right"
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          value-format="yyyy-MM-01 00:00:00"
          :picker-options="pickerOptions"
          clearable
          size="small"
        >
        </el-date-picker>
      </div>
      <div>
        <el-button type="primary" size="small" @click="handleSearchClick"
          >搜索</el-button
        >
        <el-button
          type="primary"
          size="small"
          :loading="exportLoading"
          @click="exportExcel"
          >导出EXCEL</el-button
        >
      </div>
    </div>
    <div class="table-title">生产效率-生产效率&故障率月报表</div>
    <div class="table-content">
      <Table
        ref="MainForm"
        :srouceTableData="srouceTableData"
        :columns="columns"
        :customFilter="true"
        @filter="handleFilter"
        @head-cell-click="handleHeadCellClick"
        @body-cell-click="handleBodyCellClick"
      ></Table>
    </div>
  </div>
</template>
<script>
import Table from "@/components/TableForm";
import Columns from "./columns";
import { getMainData, exportStoppageMain } from "@/api/reportForms/index";
import pickerOptions from "../components/pickerOptions";
import { downloadFile } from "@/utils/file";
export default {
  name: "FailureRateMonthly",
  components: { Table },
  data() {
    // 设置时间范围默认筛选条件：本月
    const currentYear = new Date().getFullYear();
    const currentMonth = new Date().getMonth() + 1;
    const currentDate = new Date(`${currentYear}-${currentMonth}-01 00:00:00`);

    return {
      searchMonth: [currentDate, currentDate], //默认本月
      queryParams: {
        month: [currentDate, currentDate], //默认本月
        factoryDeptName: "",
        lineName: "",
        itemCategory: "",
        itemVariety: "",
        itemAppearance: "",
        itemPackaging: "",
      },
      pickerOptions,
      columns: [],
      srouceTableData: [],
      loading: false,
      exportLoading: false,
    };
  },
  created() {
    this.getData();
  },
  mounted() {},
  methods: {
    async getData() {
      const {
        factoryDeptName,
        lineName,
        itemCategory,
        itemVariety,
        itemAppearance,
        itemPackaging,
        month,
      } = this.queryParams;

      if (!month?.length) {
        return;
      }

      const param = {
        factoryDeptName,
        lineName,
        itemCategory,
        itemVariety,
        itemAppearance,
        itemPackaging,
        startTime: this.parseTime(month[0]),
        endTime: this.parseTime(month[1]),
      };

      // 校验：不能大于12个月
      const startTimeMonth = new Date(param.startTime).getMonth() + 1;
      const startTimeYear = new Date(param.startTime).getFullYear();
      const endTimeMonth = new Date(param.endTime).getMonth() + 1;
      const endTimeYear = new Date(param.endTime).getFullYear();
      if (
        endTimeYear - startTimeYear > 1 ||
        (endTimeYear - startTimeYear == 1 && endTimeMonth >= startTimeMonth)
      ) {
        this.msgWarning("时间范围最多只能选择12个月！");
        return;
      }

      this.loading = true;
      try {
        const res = await getMainData(param);
        if (res.data) {
          const {
            produceReportRowVos,
            factoryDeptNames,
            lineNames,
            itemCategorys,
            itemVarietys,
            itemAppearances,
            itemPackagings,
            monthStrs,
          } = res.data;
          let _columns = [...Columns];
          // 累计
          _columns.push({
            prop: "sum",
            label: "累计",
            background: "rgb(237, 125, 49)",
            color: "#ffffff",
            enabledClick: true,
            customData: {
              month: "summary",
            },
            children: [
              {
                prop: "sumProduceMinutes",
                label: "生产时长(h)",
                width: 120,
                emptyValue: "-",
                formatter: (row, col) => {
                  return this.toFix(row[col.prop] / 60, 2);
                },
                background: "rgb(237, 125, 49)",
                color: "#ffffff",
                enabledClick: true,
                customData: {
                  month: "summary",
                },
              },
              {
                prop: "sumTheoryQty",
                label: "理论产量",
                width: 120,
                emptyValue: "-",
                background: "rgb(237, 125, 49)",
                color: "#ffffff",
                enabledClick: true,
                customData: {
                  month: "summary",
                },
              },
              {
                prop: "sumActualQty",
                label: "实际产量",
                width: 120,
                emptyValue: "-",
                background: "rgb(237, 125, 49)",
                color: "#ffffff",
                enabledClick: true,
                customData: {
                  month: "summary",
                },
              },
              {
                prop: "sumProduceEfficiency",
                label: "生产效率",
                width: 120,
                emptyValue: "-",
                formatter: (row, col) => {
                  return `${row[col.prop]}%`;
                },
                background: "rgb(237, 125, 49)",
                color: "#ffffff",
                enabledClick: true,
                customData: {
                  month: "summary",
                },
              },
              {
                prop: "sumAbnormalStopTimes",
                label: "故障停机次数",
                width: 120,
                emptyValue: "-",
                background: "rgb(255, 0, 0)",
                color: "#ffffff",
                enabledClick: true,
                customData: {
                  month: "summary",
                  isEquip: true,
                },
              },
              {
                prop: "sumAbnormalStopMinutes",
                label: "故障停机时长(min)",
                width: 120,
                emptyValue: "-",
                background: "rgb(255, 0, 0)",
                color: "#ffffff",
                enabledClick: true,
                customData: {
                  month: "summary",
                  isEquip: true,
                },
              },
              {
                prop: "sumAbnormalRatio",
                label: "故障率",
                width: 120,
                emptyValue: "-",
                formatter: (row, col) => {
                  return `${row[col.prop]}%`;
                },
                background: "rgb(255, 0, 0)",
                color: "#ffffff",
                enabledClick: true,
                customData: {
                  month: "summary",
                  isEquip: true,
                },
              },
            ],
          });
          // 月份
          monthStrs.forEach((month) => {
            _columns.push({
              prop: month,
              label: month,
              background: "rgb(237, 125, 49)",
              color: "#ffffff",
              enabledClick: true,
              customData: {
                month,
              },
              children: [
                {
                  prop: `${month}_produceMinutes`,
                  label: "生产时长(h)",
                  width: 120,
                  emptyValue: "-",
                  formatter: (row, col) => {
                    return this.toFix(row[col.prop] / 60, 2);
                  },
                  background: "rgb(237, 125, 49)",
                  color: "#ffffff",
                  enabledClick: true,
                  customData: {
                    month,
                  },
                },
                {
                  prop: `${month}_theoryQty`,
                  label: "理论产量",
                  width: 120,
                  emptyValue: "-",
                  background: "rgb(237, 125, 49)",
                  color: "#ffffff",
                  enabledClick: true,
                  customData: {
                    month,
                  },
                },
                {
                  prop: `${month}_actualQty`,
                  label: "实际产量",
                  width: 120,
                  emptyValue: "-",
                  background: "rgb(237, 125, 49)",
                  color: "#ffffff",
                  enabledClick: true,
                  customData: {
                    month,
                  },
                },
                {
                  prop: `${month}_produceEfficiency`,
                  label: "生产效率",
                  width: 120,
                  emptyValue: "-",
                  formatter: (row, col) => {
                    return `${row[col.prop]}%`;
                  },
                  background: "rgb(237, 125, 49)",
                  color: "#ffffff",
                  enabledClick: true,
                  customData: {
                    month,
                  },
                },
                {
                  prop: `${month}_abnormalStopTimes`,
                  label: "故障停机次数",
                  width: 120,
                  emptyValue: "-",
                  background: "rgb(255, 0, 0)",
                  color: "#ffffff",
                  enabledClick: true,
                  customData: {
                    month,
                    isEquip: true,
                  },
                },
                {
                  prop: `${month}_abnormalStopMinutes`,
                  label: "故障停机时长(min)",
                  width: 120,
                  emptyValue: "-",
                  background: "rgb(255, 0, 0)",
                  color: "#ffffff",
                  enabledClick: true,
                  customData: {
                    month,
                    isEquip: true,
                  },
                },
                {
                  prop: `${month}_abnormalRatio`,
                  label: "故障率",
                  width: 120,
                  emptyValue: "-",
                  formatter: (row, col) => {
                    return `${row[col.prop]}%`;
                  },
                  background: "rgb(255, 0, 0)",
                  color: "#ffffff",
                  enabledClick: true,
                  customData: {
                    month,
                    isEquip: true,
                  },
                },
              ],
            });
          });
          // 工厂
          _columns[0].conditionList = factoryDeptNames || [];
          // 产线
          _columns[1].conditionList = lineNames || [];
          // 品类
          _columns[2].conditionList = itemCategorys || [];
          // 品种
          _columns[3].conditionList = itemVarietys || [];
          // 品相
          _columns[4].conditionList = itemAppearances || [];
          // 包装
          _columns[5].conditionList = itemPackagings || [];

          this.columns = _columns;

          let tableData = produceReportRowVos || [];

          tableData.forEach((row) => {
            row.monthVos.forEach((month) => {
              row[`${month.produceMonthStr}_produceMinutes`] =
                month.produceMinutes;
              row[`${month.produceMonthStr}_theoryQty`] = month.theoryQty;
              row[`${month.produceMonthStr}_actualQty`] = month.actualQty;
              row[`${month.produceMonthStr}_produceEfficiency`] =
                month.produceEfficiency;
              row[`${month.produceMonthStr}_abnormalStopTimes`] =
                month.abnormalStopTimes;
              row[`${month.produceMonthStr}_abnormalStopMinutes`] =
                month.abnormalStopMinutes;
              row[`${month.produceMonthStr}_abnormalRatio`] =
                month.abnormalRatio;
            });
          });

          this.srouceTableData = tableData;
        }
      } catch (error) {
        this.columns = [...Columns];
        this.srouceTableData = [];
      }

      this.loading = false;
    },
    async handleSearchClick() {
      if (this.$refs.MainForm) {
        this.queryParams.month = this.searchMonth;
        // 清空搜索条件
        this.queryParams.factoryDeptName = "";
        this.queryParams.lineName = "";
        this.queryParams.itemCategory = "";
        this.queryParams.itemVariety = "";
        this.queryParams.itemAppearance = "";
        this.queryParams.itemPackaging = "";

        await this.getData();
        this.$refs.MainForm.updateFilterConditionValues({});
      }
    },
    async handleFilter({ column, value }, done) {
      this.queryParams[column.prop] = value?.length ? value.join(",") : "";
      await this.getData();
      done();
    },
    exportExcel() {
      const {
        factoryDeptName,
        lineName,
        itemCategory,
        itemVariety,
        itemAppearance,
        itemPackaging,
        month,
      } = this.queryParams;

      if (!month?.length) {
        return;
      }

      this.exportLoading = true;

      const param = {
        factoryDeptName,
        lineName,
        itemCategory,
        itemVariety,
        itemAppearance,
        itemPackaging,
        startTime: this.parseTime(month[0]),
        endTime: this.parseTime(month[1]),
      };
      exportStoppageMain(param)
        .then((res) => {
          downloadFile(
            res.file,
            decodeURIComponent(res.name) ||
              `生产效率-生产效率&故障率月报表${this.parseTime(
                new Date(),
                "{y}{m}{d}{h}{i}{s}"
              )}.xlsx`
          );
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
    handleHeadCellClick(column) {
      if (!column.customData) {
        return;
      }

      let month = [];
      if (column.customData.month == "summary") {
        // 点击累计表头，传入时间为当前表格的时间范围
        month = this.queryParams.month;
      } else {
        // 点击某月表头，传入所点击的单元格的时间
        const m = this.parseTime(
          column.customData.month.replace(/年|月/g, "/"),
          "{y}-{m}-01 00:00:00"
        );
        month = [m, m];
      }

      this.$router.push({
        name:
          column.customData.isEquip == true
            ? "FailureRateForMainEquipDetail"
            : "FailureRateMonthlyDetail",
        params: {
          factoryDeptName: "",
          lineName: "",
          itemCategory: "",
          itemVariety: "",
          itemAppearance: "",
          itemPackaging: "",
          month,
        },
      });
    },
    handleBodyCellClick(row, column) {
      // 空白单元格，不跳转
      if (row[column.prop] == undefined || row[column.prop] == null) {
        return;
      }
      if (!column.customData) {
        return;
      }

      let month = [];
      if (column.customData.month == "summary") {
        // 点击累计表头，传入时间为当前表格的时间范围
        month = this.queryParams.month;
      } else {
        // 点击某月表头，传入所点击的单元格的时间
        const m = this.parseTime(
          column.customData.month.replace(/年|月/g, "/"),
          "{y}-{m}-01 00:00:00"
        );
        month = [m, m];
      }

      this.$router.push({
        name:
          column.customData.isEquip == true
            ? "FailureRateForMainEquipDetail"
            : "FailureRateMonthlyDetail",
        params: {
          factoryDeptName: row.factoryDeptName,
          lineName: row.lineName,
          itemCategory: row.itemCategory,
          itemVariety: row.itemVariety,
          itemAppearance: row.itemAppearance,
          itemPackaging: row.itemPackaging,
          month,
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.table-title {
  width: 100%;
  height: 36px;
  line-height: 36px;
  text-align: center;
  border-left: 1px solid #e6e6e6;
  border-right: 1px solid #e6e6e6;
  color: #ffffff;
  background: rgb(0, 176, 80);
}
.table-content {
  height: calc(100% - 42px - 36px);
}
.search-bar {
  height: 42px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .label {
    margin-right: 5px;
    font-size: 15px;
  }
}
</style>
